package com.jy.unkown.view;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amjy.dsl.R;
import com.bumptech.glide.Glide;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.gson.Gson;
import com.jiayou.ziyou_ad.utils.MD5Util;
import com.jy.common.Tools;
import com.jy.unkown.OkHttpUtil;
import com.jy.unkown.PlayStartPauseListener;
import com.jy.unkown.UnkownVideoPoint;
import com.jy.unkown.UnkownVideoPoint2;
import com.jy.unkown.entity.UnkownAdBean;
import com.jy.unkown.page.AskDialog;
import com.jy.utils.cache.SpManager;
import com.jy.utils.utils.ApkUtils;
import com.jy.utils.utils.UI;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class UnkownSplashView extends UnkownADView implements View.OnClickListener {


    public UnkownSplashView(@NonNull Context context) {
        super(context);
    }

    public UnkownSplashView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public UnkownSplashView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    TextView progressText;
    //    UnkowVideoView unkowVideoView;
    PlayerView unkowVideoView;
    UnkownVideoPoint2 unkownVideoPoint2;
    TextView skipTxtView;
//    String jj = "{\"adKey\":\"ad777\",\"metaGroup\":[{\"adTitle\":\"开屏下载类素材\",\"appDescUrl\":\"https://adsfs.heytapimage.com/marketing/template/introduction/index.html?pkg=com.xunmeng.pinduoduo\",\"appSize\":0,\"appVersion\":\"8.0.1\",\"brandName\":\"支付宝\",\"clickUrl\":\"https://server.m.pp.cn/download/apk?appId=279979&ch_src=pm_hc&ch=default&md5=a26830e6bbeae90d365f3d1fb3601c9c&custom=0&uc_param_str=frvecpeimintnidnut\",\"creativeType\":5,\"currentIndex\":0,\"deepLink\":false,\"descs\":[\"支付宝\"],\"developerName\":\"蚂蚁金服\",\"iconUrls\":[\"https://store.heytapimage.com/img/202310/18/daae184168c873d39e7eb9c8df9c60c8.png\"],\"imageUrl\":[\"https://img1.360buyimg.com/pop/jfs/t1/231524/34/906/74318/653b709dF707117f0/6a8ad9ce839abdeb.jpg\"],\"interactionType\":2,\"materialHeight\":1920,\"materialWidth\":1080,\"packageName\":\"com.eg.android.AlipayGphone\",\"permissionUrl\":\"https://adsfs.heytapimage.com/mp/app/template/permission.html?pkg=com.xunmeng.pinduoduo\",\"privacyPolicyUrl\":\"https://m.pinduoduo.net/private_policy.html\",\"totalNum\":0,\"videoDuration\":15,\"videoUrl\":\"https://video.699pic.com/videos/73/51/50/a_H8evvP4maDWY1622735150_10s.mp4\",\"winCNoticeUrls\":[\"http://report.bjzghd.com/adx/report/event?param=729CE07510634CB8CF7EAB9DB54D889469AF1E07FEF3362D7995A9C96035108241FB0782ABC7B67C92EDA10B66E4150617B0C41E65E6A3712B8EF095FA35C22CA52B12222F027B09&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"],\"winDownloadUrls\":[\"http://report.bjzghd.com/adx/report/event?param=729CE07510634CB8CF7EAB9DB54D889469AF1E07FEF3362D7995A9C96035108241FB0782ABC7B67C92EDA10B66E4150617B0C41E65E6A3712B8EF095FA35C22CA52B12222F027B09&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"],\"winDownloadEndUrls\":[\"http://report.bjzghd.com/adx/report/event?param=729CE07510634CB8CF7EAB9DB54D889469AF1E07FEF3362D7995A9C96035108241FB0782ABC7B67C92EDA10B66E4150617B0C41E65E6A3712B8EF095FA35C22CE89C6FD0F6271325&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"],\"winInstallEndUrls\":[\"http://report.bjzghd.com/adx/report/event?param=729CE07510634CB8CF7EAB9DB54D889469AF1E07FEF3362D7995A9C96035108241FB0782ABC7B67C92EDA10B66E4150617B0C41E65E6A3712B8EF095FA35C22C23BABE7F738C8257&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"],\"winNoticeUrls\":[\"http://report.bjzghd.com/adx/report/event?param=729CE07510634CB8CF7EAB9DB54D889469AF1E07FEF3362D7995A9C96035108241FB0782ABC7B67C92EDA10B66E4150617B0C41E65E6A3712B8EF095FA35C22C8DFC4F8B1108033A&ext=D9CD8830A199CB73205AEA7D4BB43FD10EEB854ACE575FEE&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"]}],\"tracks\":[{\"type\":0,\"urls\":[\"http://tak&ext=D9CD8830A199CB73205AEA7D4BB43FD10EEB854ACE575FEE&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"]},{\"type\":1,\"urls\":[\"http://tak&ext=D9CD8830A199CB73205AEA7D4BB43FD10EEB854ACE575FEE&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"]},{\"type\":2,\"urls\":[\"http://tak&ext=D9CD8830A199CB73205AEA7D4BB43FD10EEB854ACE575FEE&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"]},{\"type\":3,\"urls\":[\"http://tak&ext=D9CD8830A199CB73205AEA7D4BB43FD10EEB854ACE575FEE&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"]},{\"type\":4,\"urls\":[\"http://tak&ext=D9CD8830A199CB73205AEA7D4BB43FD10EEB854ACE575FEE&event=width:__WIDTH__;height:__HEIGHT__;dx:__DOWN_X__;dy:__DOWN_Y__;ux:__UP_X__;uy:__UP_Y__;ts:__T_TS__;ms:__EVENT_TIME_START__;dpw:__DP_WIDTH__;dph:__DP_HEIGHT__;dpdx:__DP_DOWN_X__;dpdy:__DP_DOWN_Y__;dpux:__DP_UP_X__;dpuy:__DP_UP_Y__;sld:__SLD__\"]}],\"price\":1000}";

    @Override
    public void show() {
        setTAG("开屏广告");
        if (baseUnkownAd == null) {
            err();
            return;
        }
        View view = LayoutInflater.from(getContext()).inflate(R.layout.unkown_splash, null);
//        baseUnkownAd = new Gson().fromJson(jj, UnkownAdBean.class);
        UnkownAdBean unkownAdBean = baseUnkownAd;
        String adlogo = unkownAdBean.adlogo;
        ImageView logoImg = view.findViewById(R.id.img_logo);
        Glide.with(getContext()).load(adlogo).placeholder(R.drawable.test_app_default_icon).into(logoImg);
        progressText = view.findViewById(R.id.btn_download);
        skipTxtView = view.findViewById(R.id.skip);
        TextView native_text = view.findViewById(R.id.text_desc);

        ImageView native_main_image = view.findViewById(R.id.native_main_image);
        skipTxtView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                adClose();
            }
        });

        if (unkownAdBean.metaGroup != null && unkownAdBean.metaGroup.size() > 0) {
            UnkownAdBean.MetaGroupDTO metaGroupDTO = unkownAdBean.metaGroup.get(0);
            if (metaGroupDTO != null) {
                metaGroupDTO.videoDuration = 5;


                skipTxtView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (timeDuration >= metaGroupDTO.videoDuration) {
                            skip();
                            adClose();
                        } else {

                        }
                    }
                });

                List<String> descs = metaGroupDTO.descs;
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < descs.size(); i++) {
                    stringBuffer.append(descs.get(i)).append("\n");
                }
                native_text.setText(stringBuffer.toString());
                TextView native_brand_name = view.findViewById(R.id.app_title);
                native_brand_name.setText(metaGroupDTO.adTitle);
                if (metaGroupDTO.creativeType == 1) {
                    if (metaGroupDTO.videoDuration == 0) {
                        metaGroupDTO.videoDuration = 100;
                    }
                    //文字
                    daojishi2(skipTxtView, metaGroupDTO.videoDuration);
                } else if (metaGroupDTO.creativeType == 2) {
                    if (metaGroupDTO.videoDuration == 0) {
                        metaGroupDTO.videoDuration = 100;
                    }

                    List<String> images = metaGroupDTO.imageUrl;
                    if (images != null && images.size() > 0) {
                        Glide.with(getContext()).load(images.get(0)).into(native_main_image);
                    }
                    daojishi2(skipTxtView, metaGroupDTO.videoDuration);
                } else if (metaGroupDTO.creativeType == 5) {
                    String json = new Gson().toJson(unkownAdBean);
//                    metaGroupDTO.videoUrl = "https://1894380770-cache.supercachenet.com:9538/v1/resource/000000052a127119d7294278e2c4945551eab54f?per=00000000cf6e57b6fb3869057f71240d87da0005&ptm=1701857654&pex=1701861295&trace-id=0ac3945517018576545922650269&isp=3&region=1&province=1&app-id=6383&pck=8efc07fef17197d39c65e2407a04f616&__vid=7296762183755533609";
//                    metaGroupDTO.videoUrl = "https://v-cdn.zjol.com.cn/276985.mp4";
                    ViewStub viewStub = view.findViewById(R.id.videoStub);
                    View vv = viewStub.inflate();
                    List<String> images = metaGroupDTO.imageUrl;
                    if (images != null && images.size() > 0) {
                        Glide.with(getContext()).load(images.get(0)).into(native_main_image);
                    }

                    unkowVideoView = vv.findViewById(R.id.unkownVideoView);
                    initializePlayer(metaGroupDTO.videoUrl);

                    ImageView muteIcon = vv.findViewById(R.id.muteIcon);
                    if (videoMute) {
                        muteIcon.setImageResource(R.drawable.gdt_ic_native_volume_off);
                    } else {
                        muteIcon.setImageResource(R.drawable.gdt_ic_native_volume_on);
                    }
                    unkowVideoView.getPlayer().addListener(new Player.EventListener() {
                        @Override
                        public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                            if (playWhenReady) {

                            }
                            Player.EventListener.super.onPlayerStateChanged(playWhenReady, playbackState);
                            if (playbackState == Player.STATE_IDLE) {

                            } else if (playbackState == Player.STATE_READY) {
                                native_main_image.setVisibility(GONE);
                                Log.e(TAG, "onPrepared");
                                List<String> winloadUrls = metaGroupDTO.winLoadUrls;
                                pointPost(UnkownADView.PLAY_VIDEO, "winloadUrls 视频加载成功", winloadUrls);
                            } else if (playbackState == Player.STATE_ENDED) {

                            } else if (playbackState == Player.STATE_BUFFERING) {

                            }

                        }
                    });

                    unkownVideoPoint2 = new UnkownVideoPoint2(this, unkowVideoView, unkownAdBean.tracks);
                    unkownVideoPoint2.init();

                    muteIcon.setVisibility(VISIBLE);
                    muteIcon.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
//                            boolean mute = unkowVideoView.mute;
                            Player.AudioComponent audioComponent = unkowVideoView.getPlayer().getAudioComponent();
                            float volume = audioComponent.getVolume();

                            unkowVideoView.getPlayer().getAudioComponent().setVolume(1);
                            if (volume != 0) {
                                volume = 0;
                                muteIcon.setImageResource(R.drawable.gdt_ic_native_volume_off);
                            } else {
                                volume = 1;
                                muteIcon.setImageResource(R.drawable.gdt_ic_native_volume_on);
                            }
                            audioComponent.setVolume(volume);
                        }
                    });
                    UI.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            unkowVideoView.getPlayer().setPlayWhenReady(true);
                        }
                    }, 1000);
                    daojishi(skipTxtView, metaGroupDTO.videoDuration);
                }
                if (metaGroupDTO.interactionType == 3) {//进入下载页面
                    progressText.setText("查看详情");
                } else if (metaGroupDTO.interactionType == 2) {//下载类
                    boolean isInstall = ApkUtils.isInstall(metaGroupDTO.packageName);
                    if (isInstall) {
                        progressText.setText("点击打开");
                    } else {
                        if (metaGroupDTO != null) {
                            String downUrl = metaGroupDTO.clickUrl;
                            String key = MD5Util.getMD5(downUrl);
                            String path = SpManager.getString(key, "");
                            if (TextUtils.isEmpty(path)) {
                                progressText.setText("点击下载");
                            } else {
                                if (ApkUtils.checkApkFileIsVaild(path)) {
                                    progressText.setText("点击安装");
                                } else {
                                    progressText.setText("点击下载");
                                }
                            }
                        }
                    }

                    native_brand_name.setText(metaGroupDTO.brandName);

                } else if (metaGroupDTO.interactionType == 1) {//跳转类
                    progressText.setText("查看详情");
                }
            }

        }
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        addView(view, layoutParams);
        setOnClickListener(this);
        UnkownAdBean.MetaGroupDTO metaGroupDTO = getMetaGroupDTOBean();
        if (metaGroupDTO != null) {
            exposure(metaGroupDTO.winNoticeUrls);
        }
    }


    private void initializePlayer(String url) {
        SimpleExoPlayer player = new SimpleExoPlayer.Builder(getContext()).build();

        player.setPlayWhenReady(true);
//        player.seekTo(currentWindow, playbackPosition);
        Uri playUri = Uri.parse(url);
        MediaSource mediaSource = buildMediaSource(playUri);
        player.prepare(mediaSource, true, false);
        player.setRepeatMode(Player.REPEAT_MODE_ALL);
        unkowVideoView.setPlayer(player);
        unkowVideoView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH);
        player.setVolume(videoMute?0:1);
    }

    private MediaSource buildMediaSource(Uri uri) {
        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(getContext(), getContext().getPackageName());
        MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
        return videoSource;
    }


    Disposable daojishi;
    int timeDuration;
    boolean isStarted = false;

    private void daojishi(TextView skipTxtView, int miao) {
        if (daojishi != null) {
            daojishi.dispose();
        }
        daojishi = Observable.interval(1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        isStarted = true;
                        timeDuration++;
                        if (timeDuration < miao) {
                            skipTxtView.setText((miao - timeDuration) + "s");
                        } else {
                            daojishi.dispose();
                            skipTxtView.setText("跳过");
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });


    }


    private void daojishi2(TextView skipTxtView, int zongmiao) {
        if (daojishi != null) {
            daojishi.dispose();
        }
        daojishi = Observable.interval(1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        isStarted = true;
                        timeDuration++;
                        if (timeDuration < zongmiao) {
                            skipTxtView.setText((zongmiao - timeDuration) + "s");
                        } else {
                            skipTxtView.setText("跳过");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });


    }


    boolean isAttachedToWindow = false;

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        isAttachedToWindow = true;
        Log.e(getClass().getSimpleName(), "onAttachedToWindow");
        if (unkowVideoView != null) {
            unkowVideoView.getPlayer().setPlayWhenReady(true);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isAttachedToWindow = false;
        if (unkowVideoView != null) {
            unkowVideoView.getPlayer().setPlayWhenReady(false);
        }
        Log.e(getClass().getSimpleName(), "onDetachedFromWindow");
    }


    @Override
    void downloadSucc(String url, File progress) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载完成");
                }
            });
        }
    }

    @Override
    void downloadErr(String url, Exception e) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载失败");
                }
            });
        }
    }

    @Override
    void downloadProgress(String url, int progress) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载" + progress + "%");
                }
            });
        }
    }


    public void resume() {
        UnkownAdBean.MetaGroupDTO metaGroupDTO = getMetaGroupDTOBean();
        if (metaGroupDTO != null && isStarted) {
            if (metaGroupDTO.creativeType == 1) {
                daojishi2(skipTxtView, metaGroupDTO.videoDuration);
            } else if (metaGroupDTO.creativeType == 2) {
                daojishi2(skipTxtView, metaGroupDTO.videoDuration);
            } else if (metaGroupDTO.creativeType == 5) {
                daojishi(skipTxtView, metaGroupDTO.videoDuration);
            }
        }
    }

    public void onPause() {
        if (daojishi != null) {
            daojishi.dispose();
        }
    }

    public void onDestory() {
        try {
            if (daojishi != null) {
                daojishi.dispose();
            }
            if (unkownVideoPoint2!=null){
                unkownVideoPoint2.setStart(false);
            }
            if (unkowVideoView != null) {
                unkowVideoView.getPlayer().release();
            }
        }catch (Exception exception){

        }

    }


}